package com.wenlin.myproduction.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.wenlin.myproduction.R;
import com.wenlin.myproduction.base.BaseSwipeActivity;
import com.wenlin.myproduction.bean.PlayerBean;
import com.wenlin.myproduction.bean.TitleBean;
import com.wenlin.myproduction.binder.PlayerBinder;
import com.wenlin.myproduction.binder.TitleBinder;
import com.wenlin.myproduction.util.Checker;
import com.wenlin.myproduction.util.SPUtils;
import com.wenlin.myproduction.util.ToastUtils;
import com.wenlin.myproduction.util.UI;
import com.wenlin.myproduction.util.ValCommon;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

public class PlayerMatchActivity extends BaseSwipeActivity {
    private EditText et;
    private TextView tvLeft, tvRight;
    private RecyclerView rv;
    private Items items;
    private MultiTypeAdapter adapter;
    private Random random = new Random();

    public static void start(Context context) {
        Intent intent = new Intent(context, PlayerMatchActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getContentView() {
        return R.layout.activity_player_match;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(ValCommon.PLAYER_MATCH);

        et = findViewById(R.id.et);
        tvLeft = findViewById(R.id.tv_left);
        tvRight = findViewById(R.id.tv_right);
        rv = findViewById(R.id.rv);

        String str = SPUtils.getInstance().getString("num_per_group");
        if (Checker.hasWord(str)) {
            UI.setText(et, str);
        }

        UI.setOnClickListener(tvLeft, v -> {
            EditPlayerDialog dialog = new EditPlayerDialog(PlayerMatchActivity.this, null, this::handleClick);
            new XPopup.Builder(PlayerMatchActivity.this)
                    .asCustom(dialog)
                    .show();
        });
        UI.setOnClickListener(tvRight, v -> start());

        items = new Items();
        adapter = new MultiTypeAdapter(items);
        adapter.register(TitleBean.class, new TitleBinder());
        adapter.register(PlayerBean.class, new PlayerBinder(new PlayerBinder.OnClickListener() {
            @Override
            public void onLongClick(PlayerBean bean) {
                EditPlayerDialog dialog = new EditPlayerDialog(PlayerMatchActivity.this, bean, bean1 -> handleClick(bean1));
                new XPopup.Builder(PlayerMatchActivity.this)
                        .asCustom(dialog)
                        .show();
            }

            @Override
            public void onClickCheck(PlayerBean bean) {
                if (items == null || items.size() == 0) return;
                for (int i = 0; i < items.size(); i++) {
                    Object o = items.get(i);
                    if (o instanceof PlayerBean) {
                        PlayerBean pb = (PlayerBean) o;
                        if (pb.getName().equals(bean.getName())) {
                            pb.setChecked(!bean.isChecked());
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
            }
        }));

        rv.setLayoutManager(new GridLayoutManager(this, 1));
        rv.setAdapter(adapter);
        rv.setHasFixedSize(true);

        initData();
    }

    private void start() {
        if (items == null || items.size() == 0) return;
        String str = UI.getEtText(et);
        if (Checker.hasNoWord(str)) {
            ToastUtils.getInstance().showInfo("请输入每组人数");
            return;
        }
        int numPerGroup = Integer.parseInt(str);
        if (numPerGroup <= 0) {
            ToastUtils.getInstance().showError("每组人数必须大于0");
            return;
        }
        //取出选中的球员
        List<PlayerBean> listChecked = new ArrayList<>();
        List<PlayerBean> listUnChecked = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            Object o = items.get(i);
            if (o instanceof PlayerBean) {
                PlayerBean pb = (PlayerBean) o;
                if (pb.isChecked()) listChecked.add(pb);
                else {
                    pb.setNum(0);
                    listUnChecked.add(pb);
                }
            }
        }
        //按照star逆序排序
        for (int i = 0; i < listChecked.size(); i++) {
            for (int j = 1; j < listChecked.size(); j++) {
                if (listChecked.get(j).getStar() > listChecked.get(j - 1).getStar()
                        || (random.nextBoolean() && (listChecked.get(j).getStar() == listChecked.get(j - 1).getStar()))) {
                    PlayerBean temp = listChecked.get(j);
                    listChecked.set(j, listChecked.get(j - 1));
                    listChecked.set(j - 1, temp);
                }
            }
        }
        if (listChecked.size() == 0) {
            ToastUtils.getInstance().showError("请选择匹配球员");
            return;
        }
        int groupSize = listChecked.size() / numPerGroup;
        int realGroupSize = listChecked.size() % numPerGroup == 0 ? groupSize : (groupSize + 1);
        //匹配分组
        List<PlayerBean> listTemp = new ArrayList<>();
        for (int i = 0; i < numPerGroup; i++) {
            List<PlayerBean> listRound = listChecked.subList(i * groupSize, Math.min(i * groupSize + groupSize, listChecked.size()));
            listTemp.addAll(getRandomRound(listRound));
        }
        if (realGroupSize != groupSize) {
            List<PlayerBean> listLeft = listChecked.subList(numPerGroup * groupSize, listChecked.size());
            for (PlayerBean pb :
                    listLeft) {
                pb.setNum(realGroupSize);
            }
            listTemp.addAll(listLeft);
        }
        //格式化输出
        List<Object> listResult = new ArrayList<>();
        for (int i = 0; i < realGroupSize; i++) {
            listResult.add(new TitleBean("第" + (i + 1) + "组"));
            for (int j = 0; j < listTemp.size(); j++) {
                PlayerBean pb = listTemp.get(j);
                if (pb.getNum() == (i + 1)) listResult.add(pb);
            }
        }
        //最后把没到场的加上去
        listResult.add(new TitleBean("今天没来"));
        listResult.addAll(listUnChecked);
        if (items != null) {
            if (items.size() > 0) {
                items.clear();
                adapter.notifyDataSetChanged();
            }
            items.addAll(listResult);
            adapter.notifyDataSetChanged();
        }
    }

    private List<PlayerBean> getRandomRound(List<PlayerBean> list) {
        if (list == null || list.size() == 0) return list;
        int size = list.size();
        List<PlayerBean> result = new ArrayList<>();
        Set<String> set = new HashSet<>();
        int numGroup = 1;
        while (set.size() < list.size()) {
            PlayerBean pb = list.get(random.nextInt(size));
            if (set.contains(pb.getName())) continue;
            pb.setNum(numGroup++);
            result.add(pb);
            set.add(pb.getName());
        }
        return result;
    }

    private void handleClick(PlayerBean bean) {
        boolean has = false;
        for (int i = 0; i < items.size(); i++) {
            Object o = items.get(i);
            if (o instanceof PlayerBean) {
                PlayerBean pb = (PlayerBean) o;
                if (pb.getName().equals(bean.getName())) {
                    if (bean.getStar() == 0) {
                        items.remove(i);
                        adapter.notifyDataSetChanged();
                        return;
                    } else {
                        has = true;
                        pb.setName(bean.getName());
                        pb.setStar(bean.getStar());
                    }
                    break;
                }
            }
        }
        if (!has) items.add(bean);
        adapter.notifyDataSetChanged();
    }

    private void initData() {
        String str = SPUtils.getInstance().getString("player_list");
        if (Checker.hasNoWord(str)) return;
        List<PlayerBean> list = new ArrayList<>();
        try {
            list = new Gson().fromJson(str, new TypeToken<List<PlayerBean>>() {
            }.getType());
        } catch (JsonParseException e) {
            e.printStackTrace();
        }
        items.addAll(list);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        if (items != null && items.size() > 0) {
            List<PlayerBean> list = new ArrayList<>();
            for (Object o :
                    items) {
                if (o instanceof PlayerBean) {
                    PlayerBean pb = (PlayerBean) o;
                    list.add(pb);
                }
            }
            SPUtils.getInstance().put("player_list", new Gson().toJson(list));
        }
        SPUtils.getInstance().put("num_per_group", UI.getEtText(et));
        super.onDestroy();
    }
}
